/**
 * @description 球面坐标系计算两个经纬度之间的距离（单位米）
 * @param {Object} pointA 起始坐标 latitude:维度 longitude：经度
 * @param {Object} pointB 终点坐标 latitude:维度 longitude：经度
 * @returns {Object} 距离（单位米） 返回结构：{ success: false, msg: '', distance: 0}
 */
interface Coordinates {
	latitude: number;
	longitude: number;
}

interface DistanceResult {
	success: boolean;
	msg: string;
	distance: number;
}

const calculateDistanceInMeters = function (pointA: Coordinates, pointB: Coordinates): DistanceResult {
	let ret: DistanceResult = {
		success: false,
		msg: '',
		distance: 0,
	};
	if (!pointA || !pointB) {
		return { ...ret, msg: '请输入正确起始坐标' };
	}

	const earthRadiusM = 6371000;

	const dLat = ((pointB.latitude - pointA.latitude) * Math.PI) / 180;
	const dLon = ((pointB.longitude - pointA.longitude) * Math.PI) / 180;

	const a =
		Math.sin(dLat / 2) * Math.sin(dLat / 2) +
		Math.cos((pointA.latitude * Math.PI) / 180) *
			Math.cos((pointB.latitude * Math.PI) / 180) *
			Math.sin(dLon / 2) *
			Math.sin(dLon / 2);
	const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

	const distance = earthRadiusM * c;

	return { ...ret, success: true, distance: Math.abs(Number(distance.toFixed(6))) };
};
export default calculateDistanceInMeters;
